package com.hspedu.collection_;


import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * @Author Stringzhua
 * @Date 2024/3/10 19:40
 * description:Collection接口遍历元素方式1
 * 迭代器的使用案例
 */
public class CollectionIterator {
    @SuppressWarnings("all")
    public static void main(String[] args) {
        Collection col = new ArrayList();

        col.add(new Books("三国演义", "罗贯中", 10.1));
        col.add(new Books("小李飞刀", "古龙", 10.1));
        col.add(new Books("红楼梦", "曹雪芹", 10.1));
        col.add("jack");

//        System.out.println("col = " + col);
        //现在希望能够遍历col集合
        //step1:首先得到col集合对应的迭代器
        Iterator iterator = col.iterator();
        //step2:使用while循环来遍历集合
//        while (iterator.hasNext()) {//判断集合中是否还有数据
//            //返回下一个元素,类型是Object
//            //编译类型是Object  但是运行类型取决于真正存放的是什么样的对象
//            Object obj = iterator.next();
//            System.out.println("obj = " + obj);
//        }
        //快捷键生成itit
        //ctrl+j 显示所有快捷键的快捷键
        while (iterator.hasNext()) {
            Object next = iterator.next();
            System.out.println("next = " + next);
        }
        //3.当退出while循环后,这时iterator迭代器,指向最后的元素
//        iterator.next();//NoSuchElementException 报异常
        //4.如果希望再次遍历,需要重置我们的迭代器
        iterator = col.iterator();//重置迭代器
        while (iterator.hasNext()) {
            Object next = iterator.next();
            System.out.println("next = " + next);
        }
    }
}

class Books {
    private String name;
    private String author;
    private double price;

    public Books(String name, String author, double price) {
        this.name = name;
        this.author = author;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Books{" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                '}';
    }
}
